﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Configuration;
using System.Windows.Forms;
namespace WinServer
{
    public class TcpServer
    {
        #region Fields
        private Thread threadWatch = null;

        private Socket socketServer = null;

        private Socket socConnection = null;

        public Socket DataForwardingConnection = null;

        private DataForwardingProcessor dataForwardingProcessor = new DataForwardingProcessor("DataForwardingProcessor", 1);
        
        private FileRecordProcessor fileRecordProcessor = new FileRecordProcessor("FileRecordProcessor", 1);

        public delegate void ConectedDelegate(string message);

        public event ConectedDelegate ConectedEvent;

        public delegate void RevDataDelegate(int message);

        public event RevDataDelegate RevDataEvent;

        private bool isRuning = true;

        #endregion

        #region Server
        /// <summary>
        ///  server
        /// </summary>
        public void CreateServer()
        {
            try
            {
                string Ip = ConfigurationManager.AppSettings["IP"];
                string Port = ConfigurationManager.AppSettings["Port"];
                socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ipaddress = IPAddress.Parse(Ip);
                IPEndPoint endpoint = new IPEndPoint(ipaddress, int.Parse(Port));
                socketServer.Bind(endpoint);
                socketServer.Listen(20);
                threadWatch = new Thread(WatchConnecting);
                threadWatch.IsBackground = true;
                threadWatch.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void WatchConnecting()
        {
            try
            {
                while (isRuning)
                {
                    socConnection = socketServer.Accept();
                    EndPoint remoteEndPoint = socConnection.RemoteEndPoint;
                    IPEndPoint endPoint = remoteEndPoint as IPEndPoint;
                    if (endPoint != null)
                    {
                        IPAddress ipAddress = endPoint.Address;
                        int port = endPoint.Port;
                        if (ipAddress.ToString() == ConfigurationManager.AppSettings["WebIP"])
                        {
                           DataForwardingConnection = socConnection;
                        }

                        ConectedEvent(ipAddress.ToString());
                    }
                    ParameterizedThreadStart pts = new ParameterizedThreadStart(ServerRecMsg);
                    Thread thr = new Thread(pts);
                    thr.IsBackground = true;
                    thr.Start(socConnection);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            
        }

        private void ServerRecMsg(object socketClientPara)
        {
            try
            {
                Socket socketServer = socketClientPara as Socket;
                while (isRuning)
                {
                    byte[] arrServerRecMsg = new byte[65535];
                    int length = socketServer.Receive(arrServerRecMsg);
                    if (length > 0)
                    {
                        byte[] revByte = new byte[length];
                        Array.Copy(arrServerRecMsg, revByte, length);
                        dataForwardingProcessor.AddProcessObj(revByte);
                        fileRecordProcessor.AddProcessObj(revByte);
                        RevDataEvent(length);
                    }
                    else
                    {
                        System.Threading.Thread.Sleep(100);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// 发送命令
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="sendBytes"></param>
        public void SendCommandBytes(string ip, byte[] sendBytes)
        {
            socConnection?.Send(sendBytes, sendBytes.Length, SocketFlags.None);
        }

        public void StopServer()
        {
            isRuning = false;
            Process[] processes = Process.GetProcessesByName("WinServer");
            foreach (Process process in processes)
            {
                try
                {
                    process.Kill();
                    process.WaitForExit(); // 等待进程退出
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error killing process: {ex.Message}");
                }
            }
        }
        #endregion
    }
}